﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using CardsServer.Tools;
using CardsServer.WCF;
using Microsoft.Win32;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;

namespace CardsServer
{
    public partial class Main : Form
    {
        private ManualResetEvent allDone = new ManualResetEvent(false);
        private Socket listener;
        private bool m_Listening;
        private Thread myThread;
        
        Process MyProcess = null;
        private ContextMenuStrip m_pMenu = null;
        //private ToolStripMenuItem install = null;
        //private ToolStripMenuItem uninstall = null;
        //private ToolStripMenuItem start = null;
        //private ToolStripMenuItem stop = null;
        private ToolStripMenuItem autorun = null;
        private ToolStripMenuItem help = null;
        private ToolStripMenuItem about = null;
        //Icon icorunning;
        //Icon icostoped;
        //Icon icoApp;
        //Icon icoinstall;
        //Icon icouninst;
        VirtualServer selectvs = null;
        System.Windows.Forms.Timer t1 = null;

         /**//// <summary>
        /// 获取已设置无法关闭窗口创建参数。就是这里
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                int CS_NOCLOSE = 0x200;
                CreateParams parameters = base.CreateParams;
                parameters.ClassStyle |= CS_NOCLOSE;
                
                return parameters;
            }
        }

        public Main()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            treeView1.ImageList = imageList1;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //richTextBox2.Text += e.ExceptionObject.ToString(); 
            MessageBox.Show(e.ExceptionObject.ToString());
        }

        //private void getProcessInfo()
        //{
        //    MyProcess = Process.GetCurrentProcess();
        //    richTextBox1.Text = "进程名：" + MyProcess.ProcessName + "\r\n";
        //    richTextBox1.Text += "进程影象名：" + MyProcess.ProcessName + "\r\n"; ;
        //    richTextBox1.Text += "进程ID：" + MyProcess.Id + "\r\n"; ;
        //    richTextBox1.Text += "启动线程数：" + MyProcess.Threads.Count.ToString() + "\r\n"; ;
        //    richTextBox1.Text += "CPU占用时间：" + MyProcess.TotalProcessorTime.ToString() + "\r\n"; ;
        //    richTextBox1.Text += "线程优先级：" + MyProcess.PriorityClass.ToString() + "\r\n"; ;
        //    richTextBox1.Text += "启动时间：" + MyProcess.StartTime.ToLongTimeString() + "\r\n"; ;
        //    richTextBox1.Text += "专用内存：" + (MyProcess.PrivateMemorySize / 1024).ToString() + "K\r\n";
        //    richTextBox1.Text += "峰值虚拟内存：" + (MyProcess.PeakVirtualMemorySize / 1024).ToString() + "K\r\n";
        //    richTextBox1.Text += "峰值分页内存：" + (MyProcess.PeakPagedMemorySize / 1024).ToString() + "K\r\n";
        //    richTextBox1.Text += "分页系统内存：" + (MyProcess.PagedSystemMemorySize / 1024).ToString() + "K\r\n";
        //    richTextBox1.Text += "分页内存：" + (MyProcess.PagedMemorySize / 1024).ToString() + "K" + "\r\n"; ;
        //    richTextBox1.Text += "未分页系统内存：" + (MyProcess.NonpagedSystemMemorySize / 1024).ToString() + "K\r\n";
        //    richTextBox1.Text += "物理内存：" + (MyProcess.WorkingSet / 1024/1024).ToString() + "M\r\n";
        //    richTextBox1.Text += "虚拟内存：" + (MyProcess.VirtualMemorySize / 1024/1024).ToString() + "M" + "\r\n"; ;
            
        //}






        private void Server_Load(object sender, EventArgs e)
        {


            if (!checkDbConn())
            {
                DbSet newdbset = new DbSet(false);
                newdbset.ShowDialog();
                Server_Load(null,null);
            }
            else
            {

                my.server.Start();
                treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);
                t1 = new System.Windows.Forms.Timer();
                t1.Interval = 2000;
                t1.Tick += new EventHandler(t1_Tick);
                t1.Enabled = true;
                BindVs();
                InitUI();

            }

        }
        private void InitUI()
        {
            this.ImeMode = ImeMode.Close;
            //this.ShowInTaskbar = false;
            //this.Hide();
            notifyIcon1.DoubleClick += delegate { this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            };
            notifyIcon1.Text = my.ServiceName;
            m_pMenu = new ContextMenuStrip();
            m_pMenu.ImageList = imageList2;

            ToolStripMenuItem manager = new ToolStripMenuItem(string.Format("{0}{1}服务管理器", CardsServer.my.CorName, CardsServer.my.AppName));
            manager.ImageIndex = 0;
            manager.Tag = "manager";
            m_pMenu.Items.Add(manager);
            
            //m_pMenu.Items.Add(new ToolStripSeparator());
            //start = new ToolStripMenuItem("启动所有服务");
            //start.Tag = "start";
            //start.ImageIndex = 1;
            //m_pMenu.Items.Add(start);
            //stop = new ToolStripMenuItem("停止所有服务");
            //stop.Tag = "stop";
            //stop.ImageIndex = 2;
            //m_pMenu.Items.Add(stop);
            //m_pMenu.Items.Add(new ToolStripSeparator());


            autorun = new ToolStripMenuItem("开机自动启动服务管理器");

            autorun.Tag = "autorun";
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey rk2 = rk.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\");
            if (!rk2.GetValueNames().Contains(MyConfig.getAppValue("CorName")))
            {
                autorun.Checked = false;
            }
            else
            {
                autorun.Checked = true;
            }
            m_pMenu.Items.Add(autorun);
            m_pMenu.Items.Add(new ToolStripSeparator());
            help = new ToolStripMenuItem("帮助");
            help.Tag = "help";
            help.ImageIndex = 3;
            m_pMenu.Items.Add(help);
            about = new ToolStripMenuItem("关于");
            about.Tag = "about";
            m_pMenu.Items.Add(about);
            ToolStripMenuItem exit = new ToolStripMenuItem("退出");
            exit.Tag = "exit";
            exit.ImageIndex = 4;
            m_pMenu.Items.Add(exit);

            m_pMenu.ItemClicked += new ToolStripItemClickedEventHandler(m_pMenu_ItemClicked);
            notifyIcon1.ContextMenuStrip = m_pMenu;

            notifyIcon1.Visible = true;

        }

        private void m_pMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Tag == null)
            {
                return;
            }

            if (e.ClickedItem.Tag.ToString() == "manager")
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
            else if (e.ClickedItem.Tag.ToString() == "exit")
            {
                Exit();
            }
            else if (e.ClickedItem.Tag.ToString() == "autorun")
            {
                registe(autorun.Checked);
            }
            else if (e.ClickedItem.Tag.ToString() == "help")
            {
                try
                {
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.FileName = MyConfig.getAppValue("helpfile");
                    p.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("未找到帮助文件", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

            }
            else if (e.ClickedItem.Tag.ToString() == "about")
            {
                AboutBox aboutbox = new AboutBox();
                aboutbox.ShowDialog();
            }
        }

        /// <summary>
        ///写系统注册表 
        /// </summary>
        /// <param name="checkstate"></param>
        private void registe(bool checkstate)
        {
            if (!checkstate)
            {
                //一定要引用
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue(CardsServer.my.CorName, Application.ExecutablePath);
                rk2.Close();
                rk.Close();
                autorun.Checked = true;
            }
            else
            {
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\");
                rk2.DeleteValue(CardsServer.my.CorName);
                autorun.Checked = false;
            }
        }

        

        #region method Stop



        #endregion

        #region method Exit

        /// <summary>
        /// Exits tray application, stops server.
        /// </summary>
        private void Exit()
        {
            try
            {
                myThread.Abort();
                Application.Exit();
            }
            catch (Exception)
            {
                Application.Exit();
            }
        }
        #endregion

        void t1_Tick(object sender, EventArgs e)
        {

            foreach (TreeNode node in treeView1.Nodes)
            {
                VirtualServer vs = my.server.m_pVirtualServers.Single(p=>p.ID==((VirtualServer)node.Tag).ID);
                node.Tag=vs;
                if (vs.Enabled)
                {
                    node.ImageIndex = 1;
                    node.SelectedImageIndex = 1;
                }
                else
                {
                    node.ImageIndex = 0;
                    node.SelectedImageIndex = 0;
                }
                //treeView1.Refresh();
            }
            if (selectvs!=null)
            {
                txtAddress.Text = selectvs.Address;
                txtType.Text = selectvs.SVRType.ToString();
                txtIType.Text = selectvs.SVRIType.ToString();
                txtStartDate.Text = string.Format("{0:F}", selectvs.StartDate);
                txtState.Text = selectvs.Enabled ? "运行" : "关闭";
                txtSVRID.Text = selectvs.ID.ToString();
                txtSvrName.Text = selectvs.Name;
                btn_Start.Enabled = !selectvs.Enabled;
                btn_close.Enabled = selectvs.Enabled;
            }

        }



        private void BindVs()
        {
            treeView1.Nodes.Clear();
            foreach (WCF.VirtualServer vs in my.server.m_pVirtualServers)
            {
                TreeNode tn = new TreeNode();
                tn.Text = vs.Name;
                tn.Tag = vs;
                treeView1.Nodes.Add(tn);
               
            }
        }

        void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (my.server.m_pVirtualServers.Count(p => p.ID == ((VirtualServer)e.Node.Tag).ID) == 1)
            { 
                selectvs = my.server.m_pVirtualServers.Single(p=>p.ID==((VirtualServer)(e.Node.Tag)).ID);

                
            }
            
        }

        /// <summary>
        /// 检测数据库连接
        /// </summary>
        /// <returns></returns>
        private bool checkDbConn()
        {
            SqlConnection conn = new SqlConnection(MyConfig.getConnection().connstr);
            try
            {
                conn.Open();
                return true;
            }
            catch (Exception ex)
            {
                MyLog.writeErrorToLog("服务器连接数据库失败！"+ex.Message);
                return false;
            }
            finally {
                conn.Close();
                conn.Dispose();
            }
        }

        private void button_stop_Click(object sender, EventArgs e)
        {
            //if (serviceconfig.ServiceHostGroup.CloseAllServices())
            //{
            //    button_stop.Enabled = false;
            //    button_Start.Enabled = true;
            //    MyLog.writeInfoToLog("业务服务正常停止");
            //}
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            selectvs.Enabled = true;
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            selectvs.Enabled = false;
        }

        private void Main_Activated(object sender, EventArgs e)
        {
            t1.Enabled = true;
        }

        private void Main_Leave(object sender, EventArgs e)
        {
            t1.Enabled = false;
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Hide();
            //e.Cancel = true;
        }

        private void Main_MinimumSizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }

        private void Main_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
        }



    }
}
